package com.lgj.gateway.limiter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author: guangjie.liao
 * @Date: 2022/11/7 18:46
 * @Description: 滑动窗口限流
 */
@Component
public class SlidingWindowRateLimiter implements GatewayFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String requestPath = request.getPath().toString();
        String ip = request.getRemoteAddress().getHostString();

        String key = ip + ":" + requestPath;
        if (!isActionAllow(key,System.currentTimeMillis(),5,10)){
            exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }
    /**
     *
     * @param key 键值Key
     * @param obj 此对象在set中不能重复，如有重复会更新score
     * @param timeWin 时间窗口
     * @param maxCount 每次时间窗口容忍的最大请求数量
     * @return
     */
    public boolean isActionAllow(String key, Object obj, int timeWin, int maxCount) {
        if (StringUtils.isEmpty(key) || null == obj || timeWin == 0 || maxCount == 0) {
            return false;
        }
        long curTime = System.currentTimeMillis();
        ZSetOperations opsForZSet = redisTemplate.opsForZSet();
        opsForZSet.add(key, curTime, curTime);
        opsForZSet.removeRangeByScore(key, 0, curTime - (timeWin * 1000));
        Long count = opsForZSet.zCard(key);
        redisTemplate.expire(key, timeWin, TimeUnit.SECONDS);
        return count <= maxCount;
    }
}
